﻿using System.Threading;
using System.Threading.Tasks;

namespace 多线程
{
    public class CountDownEventDemo
    {


        private static void Main1()
        {
            /*
              信号量，用来标识线程是否执行完成 Signal 释放信号
              并行得情况下可能无法准确标识剩余信号量
              只适合多线程下得信号标识
             */
            CountdownEvent cde = new CountdownEvent(5);
            Task[] task = new Task[5];
            for (int i = 0; i < 5; i++)
            {
               
                task[i] = Task.Factory.StartNew(() =>
                {

                    System.Console.WriteLine($"线程{i}");
                    for (int j = 0; j < 1000; j++)
                    {
                        int ff = j;
                    }
                    System.Console.WriteLine($"线程{i}信号释放");
                    cde.Signal();

                    System.Console.WriteLine($"CountdownEvent 剩余信号量{cde.CurrentCount}");
                    
                });
            }
            cde.Wait();
            System.Console.WriteLine("线程执行完后");
           
            
            /*
                    并行线程0
                    并行线程4
                    并行线程3
                    并行线程1
                    并行线程2
                    并行线程4信号释放
                    并行线程3信号释放
                    并行线程0信号释放
                    并行线程2信号释放
                    CountdownEvent 剩余信号量1
                    并行线程1信号释放
                    CountdownEvent 剩余信号量2
                    CountdownEvent 剩余信号量0
                    CountdownEvent 剩余信号量4
                    CountdownEvent 剩余信号量3
                    执行完后
             
             */
            //CountdownEvent down = new CountdownEvent(5);
            //Task[] tasks = new Task[5];
            //Parallel.For(0, 5, (i) =>
            //{
            //    tasks[i] = Task.Run(() =>
            //    {
            //        System.Console.WriteLine($"并行线程{i}");
            //        for (int j = 0; j < 1000000; j++)
            //        {
            //            int ff = 0;
            //        }
            //        System.Console.WriteLine($"并行线程{i}信号释放");
            //        down.Signal();

            //        System.Console.WriteLine($"CountdownEvent 剩余信号量{down.CurrentCount}");
            //    });
            //});
            //down.Wait();
            //System.Console.WriteLine("并行线程执行完后");
        }
    }
}
